package com.zyx.mall.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zyx.mall.entity.Cart;
import com.zyx.mall.entity.OrderMaster;
import com.zyx.mall.entity.OrderItem;
import com.zyx.mall.entity.vo.OrderVo;
import com.zyx.mall.service.CartService;
import com.zyx.mall.service.OrderItemService;
import com.zyx.mall.service.OrderMasterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;

/**
 * <p>
 *  订单管理
 * </p>
 *
 * @author zyx
 * @since 2023-01-13
 */
@RestController
@RequestMapping("/api/order")
public class OrderMasterController {
    @Autowired
    private OrderMasterService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private CartService cartService;

    //添加订单
    @PostMapping("/add")
    public OrderVo addOrder(@RequestBody OrderMaster orderMaster) {
        List<OrderItem> orderItems = orderMaster.getOrderItems();
        orderService.save(orderMaster);
        String orderId = orderMaster.getId();
        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(orderId);
            orderItemService.save(orderItem);

            //删除购物车
            UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id",orderMaster.getUserId())
                            .eq("product_id",orderItem.getProductId());
            cartService.remove(updateWrapper);
        }

        //返回结果
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderId(orderId);
        orderVo.setNeedPayAmount(orderMaster.getTotalPrice());

        return orderVo;
    }

    //删除订单
    @DeleteMapping("/del")
    public Boolean delOrder(String id) {
        return orderService.removeById(id);
    }

    //查询订单数据
    @GetMapping("/list")
    public List<OrderMaster> getList() {
        return orderService.list(null);
    }

    //订单支付
    @PutMapping("/update")
    public Boolean updateOrderStatus(@RequestBody OrderMaster order){
        OrderMaster orderMaster = orderService.getById(order.getId());
        orderMaster.setStatus(order.getStatus());
        return orderService.updateById(orderMaster);
    }

    

}

